package com.hifar.test.dailydisplacement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.test.dailydisplacement.mapper.HfDailyDisplacementMapper;
import com.hifar.test.dailydisplacement.pojo.HfDailyDisplacement;
import com.hifar.test.dailydisplacement.service.IHfDailyDisplacementService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 日常位移记录 服务实现类
 * </p>
 *
 * @author system
 * @since 2025-10-15
 */
@Service
public class HfDailyDisplacementServiceImpl extends ServiceImpl<HfDailyDisplacementMapper, HfDailyDisplacement> implements IHfDailyDisplacementService {

    @Override
    public boolean checkDuplicate(Date entrustTime, String unitTypeCode, String excludeId) {
        if (entrustTime == null || StringUtils.isEmpty(unitTypeCode)) {
            return false;
        }
        
        // 格式化日期为字符串，只比较日期部分
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(entrustTime);
        
        QueryWrapper<HfDailyDisplacement> queryWrapper = new QueryWrapper<>();
        // 兼容 KingBase/PostgreSQL 数据库，使用 CAST 转换为日期类型进行比较
        queryWrapper.apply("CAST(entrust_time AS DATE) = {0}", dateStr);
        queryWrapper.eq("unit_type_code", unitTypeCode);
        queryWrapper.ne("del_flag", 1);
        
        // 编辑时排除当前记录
        if (StringUtils.isNotEmpty(excludeId)) {
            queryWrapper.ne("id", excludeId);
        }
        
        long count = this.count(queryWrapper);
        return count > 0;
    }

}

